import numpy as np
import platgo as pg
import scipy.io as sio

def eliptic(X: np.ndarray) -> np.ndarray:
    return np.sum((1e+6) ** (np.tile(np.arange(X.shape[1]), (X.shape[0], 1)) / (X.shape[1] - 1 + (1e-6))) * X ** 2, axis=1)

def rastrigin(X: np.ndarray) -> np.ndarray:
    return np.sum(0.0512 * X ** 2 - 10 * np.cos(2 * np.pi * 0.0512 * X) + 10, axis=1)

def schwefel(X: np.ndarray) -> np.ndarray:
    X = 10 * X + (4.2094e+2)
    g = X * np.sin(np.sqrt(np.abs(X)))
    temp = 500 - np.mod(X[X > 500], 500)
    g[X > 500] = temp * np.sin(np.sqrt(np.abs(temp))) - (X[X > 500] - 500) ** 2 / 10000 / X.shape[1]
    temp = np.mod(np.abs(X[X < -500]), 500) - 500
    g[X < -500] = temp * np.sin(np.sqrt(np.abs(temp))) - (X[X < -500] - 500) / 10000 / X.shape[1]
    F = 418.9829 * X.shape[1] - np.sum(g, axis=1)
    return F

class CEC_2020_F5(pg.Problem):

    def __init__(self, D=None) -> None:
        self.name = 'CEC_2020_F5'
        self.type['single'], self.type['real'] = [True] * 2
        self.M = 1
        load_path = 'CEC2020.mat'
        load_data = sio.loadmat(load_path)
        mat = []
        for k in load_data.items():
            mat.append(k)
        self.D = D
        self.O = mat[3][1][0][4][0][0][0]
        if self.D is None or self.D < 10:
            self.D = 5
            self.Mat = mat[3][1][0][4][0][0][1]
            self.S = mat[3][1][0][4][0][0][5]
        elif self.D < 15:
            self.D = 10
            self.Mat = mat[3][1][0][4][0][0][2]
            self.S = mat[3][1][0][4][0][0][6]
        elif self.D < 20:
            self.D = 15
            self.Mat = mat[3][1][0][4][0][0][3]
            self.S = mat[3][1][0][4][0][0][7]
        else:
            self.D = 20
            self.Mat = mat[3][1][0][4][0][0][4]
            self.S = mat[3][1][0][4][0][0][8]
        p = np.ceil(np.array([0.3, 0.3, 0.4]) * self.D)
        p[0] = self.D - np.sum(p[1:])
        p = np.hstack(([0], np.cumsum(p))).astype(int)
        self.S = [self.S[0][p[i]: p[i + 1]] for i in range(len(p)-1)]
        lb = [-100] * self.D
        ub = [100] * self.D
        self.borders = np.array([lb, ub])
        super().__init__()

    def cal_obj(self, pop: pg.Population) -> None:
        Y = pop.decs - np.tile(self.O[0][0: pop.decs.shape[1]], (pop.decs.shape[0], 1))
        Z = np.dot(Y, self.Mat.T)
        pop.objv = 1700 + schwefel(Z[:, self.S[0] - 1]) + rastrigin(Z[:, self.S[1] - 1]) + eliptic(Z[:, self.S[2] - 1])
        pop.objv = pop.objv.reshape(pop.objv.shape[0], 1)

    def get_optimal(self) -> np.ndarray:
        pass


if __name__ == '__main__':
    problem = CEC_2020_F5()
    alg = pg.algorithms.GA(problem=problem, maxgen=100)
    pop = alg.go(100)
    print(pop)

